package com.example.jikeyoujikeyou.office_sz.view.activity.register;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.jikeyoujikeyou.office_sz.R;
import com.example.jikeyoujikeyou.office_sz.comment.utils.ListValidate;
import com.example.jikeyoujikeyou.office_sz.model.Department;
import com.example.jikeyoujikeyou.office_sz.view.base.BaseFragment;
import com.example.jikeyoujikeyou.office_sz.view.base.BaseLvAdapter;

import java.util.ArrayList;
import java.util.List;

public class DepartmentAdapter extends BaseLvAdapter {

    private List<Department> departmentList = new ArrayList<>();
    private Context context;
    private LayoutInflater inflater;
    private Handler handler;

    public List<Department> getDepartmentList() {
        return departmentList;
    }

    public DepartmentAdapter(Context context,Handler handler) {
        this.context = context;
        this.handler = handler;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return ListValidate.isEmpty(departmentList) ? 0 : departmentList.size();
    }

    public void addItem(Department department){
        departmentList.add(department);
        notifyDataSetChanged();
    }

    @Override
    public Department getItem(int position) {
        return departmentList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder=null;
        if(null==view){
            view = inflater.inflate(R.layout.item_department_name, null, false);
            viewHolder= new ViewHolder(view);
            view.setTag(viewHolder);
            viewHolder.department_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    departmentList.remove(position);
                    final int size = departmentList.size();
                    notifyDataSetChanged();
                    Message message = handler.obtainMessage();
                    message.arg1 = departmentList.size();
                    handler.sendMessage(message);
                }
            });
        } else {
            viewHolder= (ViewHolder) view.getTag();
        }
        viewHolder.tv.setText(getItem(position).getName());
        return view;
    }

    class ViewHolder {

        View converView;
        View department_delete;
        TextView tv;

        public ViewHolder(View converView) {
            this.converView = converView;
            tv = converView.findViewById(R.id.tv_department_name);
            department_delete = converView.findViewById(R.id.department_delete);
        }
    }
}
